package com.yanqu.road.server.cmd.activity.gourdchild;


import com.yanqu.road.entity.activity.gourdchild.GourdChildConfig;
import com.yanqu.road.entity.activity.gourdchild.GourdChildUserData;
import com.yanqu.road.pb.activity.GourdChildProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.gourdchild.GourdChildModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.gourdchild.GourdChildMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

@Cmd(code = GameProtocol.S_GOURD_CHILD_USE_ENERGY_ITEM, desc = "使用体力药")
public class GourdChildUseEnergyItemCmd extends AbstractCommand {

    private int count = 0;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        GourdChildProto.GourdChildUseEnergyItemReqMsg reqMsg = GourdChildProto.GourdChildUseEnergyItemReqMsg.parseFrom(packet.getBytes());
        count = reqMsg.getCount();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {

        GourdChildConfig config = GourdChildMgr.getConfig();
        if (config == null || !ActivityMgr.activityInTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_GOURD_CHILD_ACTIVITY_NO_OPEN;
            return;
        }

        GourdChildModule module = player.getModule(GourdChildModule.class);
        GourdChildUserData userData = module.getUserData();
        if (userData == null) {
            ret = GameErrorCode.E_GOURD_CHILD_ACTIVITY_NO_UNLOCK;
            return;
        }

        ret = module.useEnergyItem(count);
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            GourdChildProto.GourdChildUseEnergyItemRespMsg.Builder builder = GourdChildProto.GourdChildUseEnergyItemRespMsg.newBuilder();
            builder.setRet(ret);
            GourdChildUserData userData = player.getModule(GourdChildModule.class).getUserData2();
            if (userData != null) {
                builder.setEnergy(userData.getEnergy());
                builder.setLastRecTime(userData.getLastRecTime());
            }else {
                builder.setEnergy(0);
                builder.setLastRecTime(System.currentTimeMillis());
            }
            player.sendPacket(ClientProtocol.U_GOURD_CHILD_USE_ENERGY_ITEM, builder);
        }
    }
}
